const Koa = require("koa"); //koa 框架
const serve = require("koa-static"); //静态资源
const path = require("path");
const body = require("koa-body"); //
const cors = require('koa2-cors');
const session = require("./utils/session.js");
const httpResult = require("./config").httpResult;



const server = new Koa(); //POST 请求的数据体里面提取键值对。

// server.use() 是用来加载中间件
server.use(cors({
    allowMethods: ['GET', 'POST', 'DELETE'],
}));


const routerMiddleWares = require("./routes");
const {
    promises
} = require("fs");
/* const categryRouter = require('./routes/category.js');
const cartRouter = require('./routes/cart.js');
const productRouter = require('./routes/product.js'); */
// 1、显示请求的url
server.use(async(ctx, next) => {
    console.log(ctx.url);
    await next(); //只要调用next函数，就可以把执行权转交给下一个中间件。
});


// 2、处理客户端的静态资源请求
server.use(serve(path.join(__dirname, "public")));

// 3、针对客户端 动态资源请求
server.use(body());

// 这个中间件是统一返回服务器响应结果的中间件
server.use(async(ctx, next) => {
    // next() 就相当于下一个中间件执行的代码
    return next().then(data => {
        ctx.body = httpResult.success(data);
    }).catch(err => {
        if (err === "401") {
            ctx.body = httpResult.untoken();
        } else if (err === "404")
            ctx.body = httpResult.notFound();
        else if (typeof err === "string")
            ctx.body = httpResult.fail(err);
        else {
            console.log(err);
            ctx.body = httpResult.error(err.message);
        }
    })
})

// 4、
// server.use(async(ctx, next) => {
//     console.log(ctx.request.body);
//     ctx.body = "hello";
// })
// 登录验证
server.use(async(ctx, next) => {
    const regArr = [/^\/category/, /^\/product/, /^\/user\/login/];
    let isNext = regArr.some(item => item.test(ctx.url));
    if (isNext) return next();
    // 如果是登陆,直接放行
    // if (ctx.url.indexOf("/user/login") !== -1) {
    //     return next();
    // } 
    else {
        const str_3rd_session = ctx.headers["authorization"];
        if (session.has(str_3rd_session)) {
            const [openid, session_key] = session.get(str_3rd_session);
            ctx.state.openid = openid;
            ctx.state.session_key = session_key;
            return next();
        } else {
            // 返回没有登陆的状态
            return Promise.reject("401");
        }
    }

});

// 统一对路由循环 use
routerMiddleWares.forEach(route => server.use(route));

server.use(async(ctx, next) => {
    return Promise.reject("404");
});
/* server.use(categryRouter);
server.use(cartRouter);
server.use(productRouter); */


server.listen(1314);